package main

import (
	"fmt"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"

	"yanxue_ai_go/pkg/common/config"
	"yanxue_ai_go/pkg/common/initialize"
	"yanxue_ai_go/pkg/common/logger"
	"yanxue_ai_go/pkg/common/middleware"
	"yanxue_ai_go/services/gateway/internal/handler"
	"yanxue_ai_go/services/gateway/internal/proxy"
	"yanxue_ai_go/services/gateway/internal/service"
)

func main() {
	// 初始化服务依赖
	initResult, err := initialize.InitializeService("gateway")
	if err != nil {
		logger.Logger.Fatal("Failed to initialize service", zap.Error(err))
	}
	defer initResult.Cleanup()

	// 初始化服务发现
	serviceRegistry := service.NewServiceRegistry()

	// 初始化服务代理
	serviceProxy := proxy.NewServiceProxy(serviceRegistry)

	// 初始化认证服务
	authService := service.NewAuthService()

	// 初始化路由
	router := setupRouter(initResult.Config, serviceProxy, authService)

	// 启动服务器
	server := &http.Server{
		Addr:         fmt.Sprintf(":%d", initResult.Config.Server.Port),
		Handler:      router,
		ReadTimeout:  time.Duration(initResult.Config.Server.ReadTimeout) * time.Second,
		WriteTimeout: time.Duration(initResult.Config.Server.WriteTimeout) * time.Second,
		IdleTimeout:  time.Duration(initResult.Config.Server.IdleTimeout) * time.Second,
	}

	// 启动服务器并等待关闭信号
	go func() {
		logger.Logger.Info("API Gateway started",
			zap.String("addr", server.Addr),
			zap.String("env", initResult.Config.App.Environment))

		if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			logger.Logger.Fatal("Failed to start server", zap.Error(err))
		}
	}()

	// 优雅关闭
	shutdownHandler := initialize.NewGracefulShutdown("gateway", server, initResult.Cleanup)
	if err := shutdownHandler.Wait(); err != nil {
		logger.Logger.Error("Shutdown error", zap.Error(err))
	}
}

func setupRouter(cfg *config.Config, serviceProxy *proxy.ServiceProxy, authService *service.AuthService) *gin.Engine {
	if cfg.App.Environment == "production" {
		gin.SetMode(gin.ReleaseMode)
	}

	router := gin.New()

	// 添加中间件
	router.Use(middleware.LoggerMiddleware())
	router.Use(middleware.RecoveryMiddleware())
	router.Use(middleware.CORSMiddleware(
		cfg.Security.CORSAllowedOrigins,
		cfg.Security.CORSAllowedMethods,
		cfg.Security.CORSAllowedHeaders,
	))

	// 健康检查
	router.GET("/health", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"status":  "healthy",
			"service": "gateway",
			"version": cfg.App.Version,
		})
	})

	// 认证相关路由
	h := handler.NewGatewayHandler(serviceProxy, authService)
	auth := router.Group("/auth")
	{
		auth.POST("/login", h.Login)
		auth.POST("/register", h.Register)
		auth.POST("/refresh", h.RefreshToken)
		auth.POST("/logout", middleware.JWTMiddleware(cfg.JWT.Secret), h.Logout)
	}

	// API代理路由（需要认证）
	api := router.Group("/api/v1")
	api.Use(middleware.JWTMiddleware(cfg.JWT.Secret))
	{
		// Agent服务代理
		agents := api.Group("/agents")
		{
			agents.Any("/*path", h.ProxyToAgent)
		}

		// MCP服务代理
		mcp := api.Group("/mcp")
		{
			mcp.Any("/*path", h.ProxyToMCP)
		}

		// RAG服务代理
		rag := api.Group("/rag")
		{
			rag.Any("/*path", h.ProxyToRAG)
		}

		// 服务状态查询
		api.GET("/services/status", h.GetServicesStatus)
	}

	// WebSocket代理
	router.GET("/ws/*path", middleware.JWTMiddleware(cfg.JWT.Secret), h.ProxyWebSocket)

	// 监控指标
	if cfg.Monitoring.PrometheusEnabled {
		router.GET("/metrics", h.PrometheusMetrics)
	}

	return router
}
